package cn.tlb.xutilsdownload.http;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import cn.tlb.utils.ClassParser;
import cn.tlb.xutilsdownload.R;

/**
 * Created by 汤林冰 on 2015/11/24 09:42.
 */
@ContentView(R.layout.activity_http)
public class HttpActivity extends AppCompatActivity {

    private String tag = getClass().getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
    }

    ///////////////////////////////////////////////////////////////////////////
    // Get and Post request
    ///////////////////////////////////////////////////////////////////////////
    @Event(R.id.get)
    private void sendGetRequest(View v) {
        DataParams dataParams = new DataParams();
        Callback.Cancelable cancelable
                = x.http().get(dataParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.i(tag, result);
                Toast.makeText(HttpActivity.this, "onSuccess!\n" + result, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(HttpActivity.this, "onError->" + ex.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                Toast.makeText(HttpActivity.this, "onFinished", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Event(R.id.post)
    private void sendPostRequest(View v) {
        DataParams dataParams = new DataParams();
        Callback.Cancelable cancelable
                = x.http().post(dataParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.i(tag, result);
                Toast.makeText(HttpActivity.this, "onSuccess!\n" + result, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(HttpActivity.this, "onError->" + ex.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                Toast.makeText(HttpActivity.this, "onFinished", Toast.LENGTH_SHORT).show();
            }
        });
    }


    ///////////////////////////////////////////////////////////////////////////
    // file download
    ///////////////////////////////////////////////////////////////////////////
    @Event(R.id.download)
    private void downloadEvent(View v) {
        DownloadParam param = new DownloadParam();
        param.setSaveFilePath("/sdcard/cntlb/1.txt");

        Callback.Cancelable cancelable = x.http().get(param, new Callback.CommonCallback<File>() {

            @Override
            public void onSuccess(File result) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                Toast.makeText(HttpActivity.this, "onFinished", Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Event(R.id.download2)
    private void download2Event(View v) {
        RequestParams params = new RequestParams("https://codeload.github.com/wyouflf/xUtils3/zip/master");
        params.setSaveFilePath("/sdcard/cntlb/master.zip");
        Callback.Cancelable cancelable = x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
                Log.i(tag, "onWaiting");

            }

            @Override
            public void onStarted() {
                Log.i(tag, "onStarted");
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                Log.i(tag, String.format("onLoading(%s, %s, %s)", total, current, isDownloading));
            }

            @Override
            public void onSuccess(File result) {
                Log.i(tag, "onSuccess: " + result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(tag, "onError: " + ex.getMessage() + "\tisOnCallback: " + isOnCallback);
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.i(tag, "onCancelled");
            }

            @Override
            public void onFinished() {
                Log.i(tag, "onFinished");
            }
        });
    }

    ///////////////////////////////////////////////////////////////////////////
    // traditional http request with progress bar
    ///////////////////////////////////////////////////////////////////////////
    @ViewInject(R.id.progressBar)
    private ProgressBar progressBar;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            progressBar.setProgress(msg.arg1);
        }
    };

    public void progressDownload(View view) {
        new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://cdn.myworld.4399sj.com/log/public/resource/map/2664/map2664.zip?1448431943");
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    int contentLength = urlConnection.getContentLength();
                    String headerField = urlConnection.getHeaderField("Content-Disposition");
                    InputStream inputStream = urlConnection.getInputStream();
                    FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/cntlb/" + headerField.substring(headerField.lastIndexOf('=') + 1));
                    byte[] bs = new byte[1024 * 8];
                    int len;
                    int total = 0;
                    int progress = 0;
                    while ((len = inputStream.read(bs)) != -1) {
                        total += len;
                        progress = total * 100 / contentLength;
                        Message.obtain(handler, 0, progress, 0).sendToTarget();
                        fileOutputStream.write(bs, 0, len);
                    }

                    fileOutputStream.close();
                    urlConnection.disconnect();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    ///////////////////////////////////////////////////////////////////////////
    // xUtils http request with progress bar
    ///////////////////////////////////////////////////////////////////////////

    @ViewInject(R.id.progressBar2)
    ProgressBar progressBar2;
    Callback.Cancelable cancelable;
    RequestParams params = new RequestParams("http://cdn.myworld.4399sj.com/log/public/resource/map/2671/map2671.zip?1448442622");
    String saveFilePath = "/sdcard/cntlb/map2671.zip";

    @Event(R.id.button4)
    private void doDownloadStart(View v) {
        params.setAutoResume(true);
        params.setAutoRename(true);
        params.setSaveFilePath(saveFilePath);
        cancelable = x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
                Log.i(tag, "onWaiting");
            }

            @Override
            public void onStarted() {
                Log.i(tag, "onStarted");
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                Log.i(tag, String.format("onLoading(%s, %s, %s)", total, current, isDownloading));
                progressBar2.setProgress((int) (current * 100 / total));
            }

            @Override
            public void onSuccess(File result) {
                Log.i(tag, "onSuccess: " + result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(tag, "onError: " + ex.getMessage() + "\tisOnCallback: " + isOnCallback);
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.i(tag, "onCancelled");
            }

            @Override
            public void onFinished() {
                Log.i(tag, "onFinished");
            }
        });
    }

    @Event(R.id.button5)
    private void doDownloadPause(View v) {
        cancelable.cancel();
    }

    @Event(R.id.button6)
    private void doDownloadCancel(View v) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("settings");
        for(String line:ClassParser.getClassText(menu).split("\n")){
            Log.d(tag, line);
        }
        return super.onCreateOptionsMenu(menu);
    }
}
